package com.sh.data.engine.domain.integration.api.record.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.sh.data.engine.common.enumDefinition.ApiTaskStatus;
import com.sh.data.engine.common.exception.BusinessException;
import com.sh.data.engine.domain.base.model.PageResult;
import com.sh.data.engine.domain.common.service.DistributedService;
import com.sh.data.engine.domain.datadev.offline.model.enums.OfflineDevJobStatusEnum;
import com.sh.data.engine.domain.integration.api.http.service.ApiHttpService;
import com.sh.data.engine.domain.integration.api.record.model.domain.ApiRunningRecordDomain;
import com.sh.data.engine.domain.integration.api.record.model.mapper.ApiRunningRecordDomainMapper;
import com.sh.data.engine.domain.integration.api.record.model.mapper.ApiRunningRecordEntityMapper;
import com.sh.data.engine.domain.integration.api.record.service.ApiRunningRecordService;
import com.sh.data.engine.domain.integration.api.webservice.service.ApiWsService;
import com.sh.data.engine.repository.dao.integration.api.http.entity.ApiHttpEntity;
import com.sh.data.engine.repository.dao.integration.api.record.ApiRunningRecordMapper;
import com.sh.data.engine.repository.dao.integration.api.record.entity.ApiRunningRecordEntity;
import com.sh.data.engine.repository.dao.integration.api.webservice.entity.ApiWsEntity;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Objects;

/**
 * @author : changkong
 * @date : 2022/3/28
 */
@Slf4j
@Service
public class ApiRunningRecordServiceImpl
    extends ServiceImpl<ApiRunningRecordMapper, ApiRunningRecordEntity>
    implements ApiRunningRecordService {

    @Lazy
    @Autowired
    private ApiHttpService apiHttpService;

    @Lazy
    @Autowired
    private ApiWsService apiWsService;

    @Autowired
    private DistributedService distributedService;

    @Autowired
    private ApiRunningRecordEntityMapper apiRunningRecordEntityMapper;

    @Autowired
    private ApiRunningRecordDomainMapper apiRunningRecordDomainMapper;

    /**
     * 添加api采集运行记录
     *
     * @param apiRunningRecordDomain
     */
    @Override
    public Long saveRecord(ApiRunningRecordDomain apiRunningRecordDomain) {
        ApiHttpEntity apiHttpEntity = apiHttpService.getById(apiRunningRecordDomain.getApiId());
        if (Objects.nonNull(apiHttpEntity)) {
            apiRunningRecordDomain.setProjectId(apiHttpEntity.getProjectId());
        } else {
            ApiWsEntity apiWsEntity = apiWsService.getById(apiRunningRecordDomain.getApiId());
            apiRunningRecordDomain.setProjectId(apiWsEntity.getProjectId());
        }

        ApiRunningRecordEntity apiRunningRecordEntity = apiRunningRecordEntityMapper.map(apiRunningRecordDomain);
        if (null == apiRunningRecordDomain.getId()) {
            boolean save = this.save(apiRunningRecordEntity);
            if (!save) {
                throw new BusinessException("保存api采集记录失败");
            }
            return apiRunningRecordEntity.getId();
        } else {
            this.updateById(apiRunningRecordEntity);
            return apiRunningRecordDomain.getId();
        }
    }

    @Override
    public PageResult<ApiRunningRecordEntity> getRunningRecordPageList(
        Integer pageNum, Integer pageSize, Long taskId, Integer taskStatus, Integer executeType,
        Integer ignored) {
        LambdaQueryWrapper<ApiRunningRecordEntity> lambdaQueryWrapper = new LambdaQueryWrapper<ApiRunningRecordEntity>()
            .eq(null != taskId, ApiRunningRecordEntity::getApiId, taskId)
            .eq(
                null != taskStatus && taskStatus > 0,
                ApiRunningRecordEntity::getTaskStatus,
                taskStatus)
            .eq(null != executeType, ApiRunningRecordEntity::getExecuteType, executeType)
            .orderByDesc(ApiRunningRecordEntity::getStartTime);
        if (Objects.nonNull(ignored)) {
            if (Objects.equals(ignored, 1)) {
                lambdaQueryWrapper.eq(ApiRunningRecordEntity::getIgnored, 1);
            } else {
                lambdaQueryWrapper.and(e -> e.eq(ApiRunningRecordEntity::getIgnored, 0).or()
                    .isNull(ApiRunningRecordEntity::getIgnored));
            }
        }
        Page<ApiRunningRecordEntity> page =
            this.page(
                new Page<>(pageNum, pageSize), lambdaQueryWrapper
            );

        return new PageResult<>(page.getTotal(), page.getRecords(), pageNum, pageSize);
    }

    @Override
    public ApiRunningRecordDomain getApiRunningRecord(Long id) {
        return apiRunningRecordDomainMapper.map(this.getById(id));
    }

    @Override
    public void updateApiRunningRecord() {
        String ipInfo = distributedService.getCurrentIpInfo();
        LambdaQueryWrapper<ApiRunningRecordEntity> eq1 = new LambdaQueryWrapper<>(
            ApiRunningRecordEntity.class)
            .eq(ApiRunningRecordEntity::getTaskStatus,
                ApiTaskStatus.running.getTaskStatus())
            .eq(ApiRunningRecordEntity::getIpAddress, ipInfo);
        List<ApiRunningRecordEntity> list = this.list(eq1);
        list.forEach(e -> e.setTaskStatus(OfflineDevJobStatusEnum.CANCEL.getCode()));
        this.updateBatchById(list);
    }
}
